package com.gy.education.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.view.Display;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2015/12/25.
 */
public class BitmapUtil {

    private static int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // 使用最大可用内存值的1/8作为缓存的大小。
    private static int cacheSize = maxMemory / 8;
    //缓存
    private static LruCache<String, Bitmap> mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // 重写此方法来衡量每张图片的大小，默认返回图片数量。
            return bitmap.getByteCount() / 1024;
        }
    };


    /**
     * 设置图片大小
     */
    public static void setImageViewSize(Context context, ImageView imageView) {
        int screenWidth = getScreenWidth(context);
        int screenHeight = getScreenHeight(context);
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();
        lp.width = screenWidth;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        imageView.setLayoutParams(lp);
        imageView.setMaxWidth(screenWidth);
        imageView.setMaxHeight(screenHeight);
    }

    /**
     * 加入缓存
     *
     * @param key
     * @param bitmap
     */
    public static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache.size() > 20) {
            mMemoryCache.evictAll();
        }
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    /**
     * 从缓存中获取
     *
     * @param key
     * @return
     */
    public static Bitmap getBitmapFromMemCache(String key) {
        return mMemoryCache.get(key);
    }

    //    class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    //        // 在后台加载图片。
    //        @Override
    //        protected Bitmap doInBackground(Integer... params) {
    //            final Bitmap bitmap = decodeSampledBitmapFromResource(
    //                    context.getResources(), params[0], 100, 100);
    //            addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
    //            return bitmap;
    //        }
    //    }


    /**
     * 计算缩放比
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 计算缩放比例
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 返回缩放后的bitmap
     *
     * @param res
     * @param resId
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true，来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

    /**
     * oom解决,加入缓存
     * 背景解决方法
     * img.setBackgroundDrawable(bitmapDrawale)
     * BitmapDrawable bmdrawable = new BitmapDrawable(context.getResources(), bitmap);
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;

        InputStream is = context.getResources().openRawResource(resId);
        Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
        return bm;
    }

    /**
     * oom解决,不加入缓存
     * 背景解决方法
     * img.setBackgroundDrawable(bitmapDrawale)
     * BitmapDrawable bmdrawable = new BitmapDrawable(context.getResources(), bitmap);
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMapLru(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;

        InputStream is = context.getResources().openRawResource(resId);
        Bitmap bm = BitmapFactory.decodeStream(is, null, opt);

        String url = String.valueOf(resId);
        addBitmapToMemoryCache(url, bm);
        return bm;
    }


    /**
     * 加载网络图片
     *
     * @param onLoadImageListener
     */
    public static void onLoadImage(final Context context, final String url, final OnLoadImageListener onLoadImageListener) {
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                onLoadImageListener.OnLoadImage((Bitmap) msg.obj, null);
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                URL imageUrl = null;
                try {
                    imageUrl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                    InputStream inputStream = conn.getInputStream();

                    BitmapFactory.Options opt = new BitmapFactory.Options();
                    opt.inPreferredConfig = Bitmap.Config.RGB_565;
                    opt.inPurgeable = true;
                    opt.inInputShareable = true;

                    byte[] bt = getBytes(inputStream); // 注释部分换用另外一种方式解码
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bt, 0, bt.length);
                    //                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, opt);
                    //                    addBitmapToMemoryCache(url, bitmap);
                    //                    BitmapDrawable bmdrawable = new BitmapDrawable(context.getResources(), bitmap);
                    Message msg = new Message();
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;

        while ((len = is.read(b, 0, 1024)) != -1) {
            baos.write(b, 0, len);
            baos.flush();
        }
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    public interface OnLoadImageListener {
        public void OnLoadImage(Bitmap bitmap, String bitmapPath);
    }

    private static Map<String, SoftReference<Drawable>> imageCache;

    /**
     * 软引用缓存
     *
     * @param imageUrl
     * @return
     */
    public static Drawable getDrawable(String imageUrl) {
        Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            if (softReference.get() != null) {
                return softReference.get();//得到缓存中的Drawable
            }
        }
        return null;
    }

    public static void saveBitmap(Bitmap bitmap, String path) throws IOException {
        File file = new File(path + "/image.png");
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




































